'''
Author: your name
Date: 2021-03-07 16:56:52
LastEditTime: 2021-05-13 16:45:12
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /tinyms/tinyms-api/apps/auth/menu/service.py
'''
import json
from app import db
from .model import Menu
from .menuDto import  MenuDto

class MenuService():
    '''
    查询所有菜单列表(包含按钮)
    '''
    def list_all(self):
        #查询父菜单
        menus = []
        menu = MenuDto(None,None)
        #调用递归方法获取菜单集合
        rootMenus = self.recursive_list(None,'1',menu,menus)
        #将菜单集合转化为json格式
        # menus_json = json.dumps(rootMenus, ensure_ascii=False,default=lambda o: o.__dict__, sort_keys=True)
        menus_json = json.dumps(rootMenus, ensure_ascii=False,default=lambda o: o.__dict__)
        return menus_json
    
    '''
    查询所有选中的菜单
    '''
    def list_checked(role_pk):
        sql = """
           	select m.*, rm.checked
            from sys_menu m
            left join sys_rolesmenu rm
            on m.menu_pk = rm.fk_menu_pk
            where 1 = 1
			and rm.fk_roles_pk in("""+role_pk+""")
			and rm.checked='1'
            """
        res = db.session.execute(sql)
        all_res_list = res.fetchall()
        return all_res_list
    '''
    查询所有选中的菜单
    '''
    
    def btns_checked(role_pk):
        sql = """
           	select m.menu_url
            from sys_menu m
            left join sys_rolesmenu rm
            on m.menu_pk = rm.fk_menu_pk
            where 1 = 1
            and m.menu_type='1'
			and rm.fk_roles_pk in("""+role_pk+""")
			and rm.checked='1'
            """
        res = db.session.execute(sql)
        all_res_list = res.fetchall()
        return all_res_list

    '''
    根据主键获取菜单信息
    '''
    def getMenuInfo(menu_pk):
        menu = Menu.query.get(menu_pk)
        return menu
    '''
    根据主键删除数据
    '''
    def delete(menu_pk):
        menu = Menu.query.get(menu_pk)
        db.session.delete(menu)
        db.session.commit()
    '''
    查询菜单树
    '''
    def menu_list(self):
        #查询父菜单
        menus = []
        menu = MenuDto(None,None)
        #调用递归方法获取菜单集合
        rootMenus = self.recursive_list('0','1',menu,menus)
        #将菜单集合转化为json格式
        # menus_json = json.dumps(rootMenus, ensure_ascii=False,default=lambda o: o.__dict__, sort_keys=True)
        menus_json = json.dumps(rootMenus, ensure_ascii=False,default=lambda o: o.__dict__)
        return menus_json


    '''
    递归查询菜单
    type为菜单类型 1菜单
    '''
    def recursive_list(self,type,pk,menudto,menus):
        # 记录子菜单列表
        children = []
        #查询父菜单
        if type is not None:
            menuParents = Menu.query.filter(Menu.menu_type==type,Menu.menu_parent==pk).all()
        else:
            menuParents = Menu.query.filter(Menu.menu_parent==pk).all()
        #遍历父菜单查询对应子菜单
        for menu in menuParents:
            #临时菜单实体
            tmp_menudto = MenuDto(menu,None)
            #如果是第一级菜单
            if menu.menu_parent == '1':
                #将菜单加入到list中
                menus.append(tmp_menudto)
                #继续遍历下级菜单
                self.recursive_list(type,menu.menu_pk,tmp_menudto,menus)
            else:
                #将下级菜单放到临时集合中
                children.append(tmp_menudto)
                #继续遍历下一级菜单
                self.recursive_list(type,menu.menu_pk,tmp_menudto,menus)
        #将子菜单集合赋给当前的menu中的子菜单集合，[]集合也加进去，否则vue中会报错
        menudto.children = children
        return menus


    '''
    保存菜单
    '''
    def save(menu):
        db.session.add(menu)
        db.session.commit()

    '''
    更新数据
    '''
    def update(menu):
        tmp_menu = Menu.query.get(menu.menu_pk)
        tmp_menu.menu_name = menu.menu_name
        tmp_menu.menu_icon = menu.menu_icon
        tmp_menu.menu_url = menu.menu_url
        tmp_menu.menu_type = menu.menu_type
        tmp_menu.menu_number = menu.menu_number
        tmp_menu.menu_status = menu.menu_status
        tmp_menu.sys_type = menu.sys_type
        if menu.menu_parent:
            tmp_menu.menu_parent = menu.menu_parent
        db.session.commit()

    ''' 
    分页方法
    '''
    def pages():
        pages = Menu.query.paginate(int(page),30,False) #flask_sqlalchemy提供分页方法.paginate
        return pages